<?php
class testAction extends apiAction
{
	public $_mod = '';
	public $cache = '';
	public $cache_name = '';
    public function _initialize() {
		parent::_initialize();
    }
    
	public function index() {
		
		$id = $this->_get('id','intval');
		$answer = $this->_get('answer');
		$answer = trim($answer,',');
		$answer_arr = explode(',',$answer);
		//计算 考试结果
		$this->cache_name = 'test/'.$id;
		$test_list = F($this->cache_name);
		$test_num = count($test_list);
		$answer_num = count($answer_arr);
		if($test_num>$answer_num){
			//说明/提交的答案 选项不足
			$data['msg'] = '获取失败,提交的答案比题目少';
			$data['status'] = 0;
			$data['data'] = array();
			$this->APIreturn($data);
		}
		$yes = 0;//正确的数量
		foreach($test_list as $k=>$v ){
			if($v['answer'] == $answer_arr[$k]){
				++$yes;
			}
		}
		
		
		$is_pass = $yes/$test_num>=0.8?1:0;//是否达到正确率
		//记录到考试结果记录表
		$result['time'] = time();
		$result['openid'] = $this->user_info['openid'];
		$result['class_id'] = $id;
		$result['is_pass'] = $is_pass;
		//先判断他之前通过这个节了没有
		if(D('test_result')->where(array('class_id'=>$id,'openid'=>$this->user_info['openid'],'is_pass'=>1))->find()){
			
		}else{
			D('test_result')->add($result);
		}
		
		
		//历史考核数据
		$test_result = D('test_result')->where(array('class_id'=>$id))->select();
		$total_num = count($test_result);
		$total_pass = 0;
		$today_num = 0;
		$today_pass = 0;
		$today_time =  strtotime(date('Y-m-d'));
		foreach($test_result as $k => $v){
			if($v['is_pass']==1){
				++$total_pass;//历史通过数
				if($v['time']>$today_time){
					++$today_pass;//今日的通过数
				}
			}
			if($v['time']>$today_time){
				++$today_num;//今日的考核数
			}
		}
		$total_pass = ceil($total_pass*100/$total_num);
		$today_pass = ceil($today_pass*100/$today_num);
		
		$list['is_pass'] = $is_pass;
		$list['total_num'] = $total_num;
		$list['total_pass'] = $total_pass;
		$list['today_num'] = $today_num;
		$list['today_pass'] = $today_pass;
		//找出下一题的id;
		
		$next_id = 8;
		$next_url = U('home/examination/index',array('id'=>$next_id));
		
		$list['url'] = $is_pass==0?U('home/rookie/index',array('id'=>$id)):$next_url;
		$list['result_title'] = $is_pass==0?'考核失败!':'考核通过!';
		$list['result_right'] = $yes;
		$list['result_wrong'] = $test_num-$yes;
		$list['result_content'] = '考核共'.$test_num.'道题，答对'.ceil(0.8*$test_num).'道题以上可通过考核。';
		$data['msg'] = '考试结果';
		$data['status'] = 1;
		$data['data'] = $list;
		$this->APIreturn($data);
    }
}